package cn.itsource.org.controller;

import cn.itsource.basic.page.PageList;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
/*
*    @GetMapping 查询一条数据 或者所有数据
*    @PostMapping 分页查询
*    @PutMapping  新增或者修改数据
*    @DeleteMapping 删除数据
*    @PatchMapping 批量操作
* */

@RestController
@RequestMapping("/employee")
@Api(value = "员工的API",description="员工相关的CRUD功能")//Swagger注解
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @GetMapping("/{id}")/*url地址里面写参数占位符 eg: http://localhost:8080/dept/2  */
    @ApiOperation(value = "通过ID查询一条数据")   /*@PathVariable 从url路径中取值*/
    public Employee queryOne(@ApiParam(name="ID属性",required = true) @PathVariable("id") Long id){
       return employeeService.queryOne(id);
    }

    //查询全部
    @GetMapping /* 什么都不写 http://localhost:8080/dept*/
    public List<Employee> queryAll(){
        return employeeService.queryAll();
    }

    //分页查询
    @PostMapping("/list")
    //@RequestBody作用：到请求体中去取值
    //    之前：把参数转成 id=5&name=zs 放到请求体中
    //    现在：把参数转成 json字符串 放到请求体中 这种要取值 就需要@RequestBody这个注解
    public PageList queryPage(@RequestBody EmployeeQuery query){
        System.out.println(query);
        return employeeService.queryPage(query);
    }

    //删除数据
    @DeleteMapping("/{id}")//@PathVariable 从url路径中取值
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            employeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，稍后再试");
        }
    }

    //新增或者修改数据
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Employee employee){
        try {
            if(employee.getId() == null){
                employeeService.add(employee);
            }else {
                employeeService.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，稍后再试");
        }
    }

    //批量删除
    @PatchMapping
    public AjaxResult bachDelete(@RequestBody List<Long> ids){
        try {
            employeeService.bachDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }




}
